import React, { Component } from "react"
import { connect } from 'react-redux'
import { deepFullCopy, messages } from "share/common"
import Selector from "components/selector"
import { Modal, Form, Input, Select, message } from 'antd'
import ResizeTable from "components/resize-table"
import interfaceService from "containers/financial-account/interface-definition/interface-service";

const FormItem = Form.Item;
const { Option } = Select;

@connect(mapStateToProps)
@Form.create()
class ObjectModal extends Component {

  state = {
    saveLoading: false,
    infoVisible: false,
    infoData: []
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.visible === true && nextProps.visible !== this.props.visible) {
      this.props.form.resetFields();
    }
  }

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { user, setOfBooksId, cancel, accountingMapDebugCommand } = this.props;
        let params = {
          businessCode: values.businessCode,
          entityType: Number(values.type),
          operatorOid: user.userOID,
          journalType: values.record.templateCode,
          transactionDetailIds: values.transactionDetailIds ? [values.transactionDetailIds] : [],
          forceRefresh: true,
          setOfBooksId,
          isPreview: true,
          accountingMapDebugCommand
        };
        this.setState({ saveLoading: true });
        interfaceService.debug(params).then(res => {
          cancel();
          this.setState({
            infoData: res.data,
            infoVisible: true,
            saveLoading: false
          })
        }).catch(e => {
          this.setState({ saveLoading: false });
          message.error(e.response.data.message);
        })
      }
    })
  };

  render() {
    const { visible, cancel, tenant, columns, setOfBooksId } = this.props;
    const { saveLoading, infoVisible, infoData } = this.state;
    const { getFieldsValue, getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 14 },
    };
    let temp = deepFullCopy(columns);
    temp.splice(columns.length - 1, 1);
    let infoColumns = temp.map((item, index) => {
      if (index !== 0 && index !== 1) {
        item.render = (value,record) => {
          const { refElementTargetCode, actualElementTargetCode } = ((record.matchResultDetailDTOS || [])[index - 2] || {});
          return (<div>
            <div>{refElementTargetCode}</div>
            <div>{actualElementTargetCode}</div>
          </div>)
        }
      }
      return item
    });
    const result = getFieldsValue();
    return (
      <div>
        <Modal
          visible={visible}
          onOk={this.handleOk}
          confirmLoading={saveLoading}
          onCancel={cancel}
          title={'匹配组调试'}
        >
          <Form>
            <FormItem label={messages('common.document.code')/*单号*/} {...formItemLayout}>
              {getFieldDecorator('businessCode', {
                rules: [{ required: true, message: messages('common.please.input')/*请输入*/ }],
              })(
                <Input placeholder={messages('common.please.input')/*请输入*/} autoComplete='off'/>
              )}
            </FormItem>
            <FormItem label={messages('finance-2.key84')/*单号类型*/} {...formItemLayout}>
              {getFieldDecorator('type', {
                rules: [{ required: true, message: messages('common.select')/*请选择*/ }]
              })(
                <Select placeholder={messages('common.select')/*请选择*/}>
                  <Option key={'1002'}>报销单</Option>
                  <Option key={'3001'}>借款单</Option>
                  <Option key={'1008'}>还款单</Option>
                  <Option key={'7001'}>付款申请单</Option>
                </Select>
              )}
            </FormItem>
            <FormItem label={'凭证'} {...formItemLayout}>
              {getFieldDecorator('record', {
                rules: [{ required: true, message: messages('common.select')/*请选择*/ }]
              })(
                <Selector
                  entity
                  selectorItem={{
                    url: '/ledger/api/journal/template/query',
                    key: 'id',
                    label: 'templateName'
                  }}
                  params={{
                    setOfBooksId,
                    isEnable: true
                  }}
                />
              )}
            </FormItem>
            {
              result.type && result.businessCode && result.record && (
                <FormItem label={'流水号'} {...formItemLayout}>
                  {getFieldDecorator('transactionDetailIds')(
                    <Selector
                      type='entry-information'
                      params={{
                        businessCode: result.businessCode,
                        tenantId: tenant.id,
                        journalTemplateId: result.record.id,
                        type: Number(result.type)
                      }}
                    />
                  )}
                </FormItem>
              )
            }
          </Form>
        </Modal>
        <Modal
          visible={infoVisible}
          footer={null}
          width={900}
          title={messages('finance-2.key85')/*预览信息*/}
          onCancel={() => this.setState({ infoVisible: false })}
        >
          <ResizeTable
            dataSource={infoData}
            rowKey={'index'}
            bordered
            pagination={false}
            scroll={{ x: true }}
            columns={infoColumns}
          />
        </Modal>
      </div>
    )
  }

}


function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    user: state.login.user
  }
}

export default ObjectModal
